<?php

namespace App\Http\Controllers\ChinaBank;

use App\Models\ChinaBank\CardModel;
use App\Models\ChinaBank\CardTypeModel;
use App\Models\ChinaBank\GoodsModel;
use App\Models\ChinaBank\OrderGoodsModel;
use App\Models\ChinaBank\OrderModel;
use App\Models\ChinaBank\ShopAddressModel;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use App\Models\UserModel;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use App\Http\Controllers\ChinaBank\BankApiController;
use Overtrue\LaravelWeChat\Facade as EasyWeChat;

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        //检查是否登录
    }

    public function error($msg,$url='')
    {
        return view("chinabank/app/error",["msg"=>$msg,'url'=>$url]);
    }

    /**
     * Show the application dashboard.
     * @param $request Request
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function index(Request $request)
    {
        return view('chinabank/app/index');
    }

    /**
     * 获取验证码
     * */
    public function sendCode(Request $request){
        $mobile = $request->input('mobile');
        $time   = $request->session()->get("mobileTime",time()-100);
        if(time() - $time < 60){
            return self::send(2003,"操作太频繁");
        }
        $code   = rand(1000,9999);
        $smsAccount = "4000219000";
        $smsPwd     = "4000219000123";
        $content    = "【同铸商务】您的验证码为{$code}，如非本人操作请忽略！";
        //$content    = urlencode($content);
        $data       = [
            "username"=>$smsAccount,
            "password"=>md5($smsAccount.md5($smsPwd)),
            "mobile"=>$mobile,
            "content"=>$content
        ];
        $url = "http://smsapi.sungoin.com:9001/smsSend.do?";
        $url = $url.http_build_query($data);
        $res = (new Client())->get($url,[])->getBody()->getContents();
        //$res = 23;
        if($res > 0){
            $request->session()->put("mobile",$mobile);
            $request->session()->put("mobileCode",$code);
            $request->session()->put("mobileTime",time());

            return self::send(200,"SUCCESS",['mobileCode'=>$code]);
        }else{
            return self::send(2003,"获取错误");
        }
    }

    public function checkCode(Request $request){

        $mobile = $request->input('mobile');
        $code   = $request->input('code');
        if($mobile == $request->session()->get("mobile") && $code == $request->session()->get("mobileCode")){
            return self::send();
        }else{
            return self::send(2003,"验证码错误");
        }
    }
    /**
     * 兑换首页
     * @param $request Request
     * @return mixed
     * */
    public function exchange(Request $request)
    {
        $secret     = trim($request->input('secret',''));
        $account    = trim($request->input('account',''));
        $pwd        = trim($request->input('pwd'));
        //$account    = "CCC3";
        //$pwd        = "PPP3";

        if(empty($secret) && empty($account))
        {
            return $this->error("参数错误");
        }

        if(empty($secret)){


            //检查券有效性
            $cardInfo   = CardModel::where(["account"=>$account,'password'=>$pwd])->first();
            if(is_null($cardInfo))
            {
                return $this->error("不存在此账号");
            }

        }else{

            $secret = BankApiController::decrypt($secret);
            $secret = \GuzzleHttp\json_decode($secret);
            $cards  = $secret->ticketS;
            $card   = $cards[0];
            $account= $card->ticketCode;
            $pwd    = $card->pwd;
        }

        //检查卡券是否存在
        $cardInfo   = CardModel::where("account",$account)->where('password',$pwd)->first();
        if(is_null($cardInfo))
        {
            return $this->error("不存在此账号");
        }

        //检查卡券是否已经领取，如领取了跳转到订单页面
        if($cardInfo->order_id > 0){

            //跳转到商品界面
            return $this->orders($request);
        }

        $cardType   = CardTypeModel::find($cardInfo->type);
        $goods      = GoodsModel::whereIn('id',explode(',',$cardType->goods))->first();
        $address    = ShopAddressModel::where('shop',$goods->shop)->get()->toArray();
        foreach ($address as &$ad){
            $ad['distance'] = 0;
        }
        $address    = \GuzzleHttp\json_encode($address,JSON_UNESCAPED_UNICODE);
        $goods->type = $cardType->name;
        $contents = explode("\n",$goods->content);
        $goods->content = array_splice($contents,0,2);
        $request->session()->put("account",$account);

        $APIs = ["getLocation"];
        $officialAccount = EasyWeChat::officialAccount();
        $wxconfig = $officialAccount->jssdk->buildConfig($APIs, $debug = false, $beta = false, $json = true);

        return view('chinabank/app/exchange',["shopAddress"=>$address,'goods'=>$goods,'wxconfig'=>$wxconfig]);
    }


    public function exchangeAction(Request $request){

        $account    = $request->session()->get("account");
        $userId     = $request->session()->get('userId');
        $card       = CardModel::where('account',$account)->first();
        $cardType   = CardTypeModel::find($card->type);

        //进行检查
        if($card->order_id > 0){

            return view("chinabank/app/error",["msg"=>"卡券已经被使用"]);
        }

        $orderInfo  = [
            "order_sn"      => date('YmdHis').rand(1000,9999),
            "user_id"       => $userId,
            "bank_order_id" => $card->bank_order_id,
            "card_id"       => $card->card_id,
            "book_date"     => $request->input('bookDate'),
            "book_shop"     => $request->input('shop'),
            "user_name"     => $request->input('name'),
            "user_mobile"   => $request->input('mobile'),
            "user_note"     => $request->input('note'),
            'status'        => 0
        ];
        $order = OrderModel::create($orderInfo);

        //将券，设置为已使用
        $card->update(['order_id'=>$order->order_id]);

        //添加订单产品
        $goods  = explode(",",$cardType->goods);

        foreach ($goods as $gid)
        {
            OrderGoodsModel::create(["order_id"=>$order->order_id,"goods_id"=>$gid,"num"=>1]);
        }
        //兑换成功，跳转到订单界面
        return $this->error("恭喜，兑换成功!",route("orders"));
    }

    public function orders(Request $request){
        $status     = ["待确认","待拍摄","已完成","已关闭"];
        $userId     = $request->session()->get("userId");
        $orders     = OrderModel::where('user_id',$userId)->whereNull('deleted_at')->get();


        foreach($orders as $key =>$order)
        {
            $order->statusName = $status[$order->status];
            //获取产品
            $goods  = OrderGoodsModel::where('order_id',$order->order_id)->first();
            $goods  = GoodsModel::find($goods->goods_id);
            $order->goodsName   = $goods->name;
            $order->price       = $goods->price;
            $order->thumb_img   = $goods->thumb_img;

            //门店
            $shop   = ShopAddressModel::find($order->book_shop);
            $order->shopName = $shop->name;

            //卡片
            $card   = CardModel::find($order->card_id);
            $order->cardAccount = $card->account;
            $order->cardPwd     = $card->password;
        }
        $orders     = json_encode($orders);
        return view("chinabank/app/orders",['orders'=>$orders]);
    }

    public function goods(Request $request){
        $goodsId    = $request->input('id');
        $goods  = GoodsModel::find($goodsId);
        $goods->images = explode(",",$goods->images);
        return view('chinabank/app/goods',['goods'=>$goods]);
    }

    public function checkCard(Request $request){
        $card = trim($request->input('account'));
        $pwd  = trim($request->input('pwd'));

        $hasCard = CardModel::where('account',$card)->where('password',$pwd)->first();
        if($hasCard){
            return self::send();
        }else{
            return self::send(2001,"卡号密码不正确请重试");
        }
    }
}
